import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/config/res_zero_tube_entity.dart';
import 'package:flutter_deer/database/order_status.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/base_dialog.dart';
import 'package:flutter_deer/widgets/dialog/error_dialog.dart';
import 'package:flutter_deer/widgets/dialog/pay_success_dialog.dart';
import 'package:flutter_deer/widgets/search_box.dart';
import 'package:get/get.dart';


/// 合并油单弹窗
class OrderPayMobileDialog extends StatefulWidget {
  const OrderPayMobileDialog(this.msg, {super.key});

  final String msg;

  @override
  State<OrderPayMobileDialog> createState() => _OrderPayMobileDialogState();
}

class _OrderPayMobileDialogState extends State<OrderPayMobileDialog> {
  final AppZeroModConfig? config = AppZeroModConfig.getConfig();
  CashierPageProvider mProvider = Get.find<CashierPageProvider>();

  // 1. 声明搜索框焦点控制器
  late FocusNode _searchFocusNode;
  StreamSubscription<String>? _orderMqttIdSubscription;

  @override
  void initState() {
    super.initState();
    mProvider.orderPollFinanceId = '';
    mProvider.orderStatus.value = '';
    // 2. 初始化搜索框焦点控制器
    _searchFocusNode = FocusNode();
    // 延迟一帧确保Widget构建完成后请求焦点
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _searchFocusNode.requestFocus();
      // 监听订单状态推送
      _orderMqttIdSubscription = mProvider.orderMqttId.listen((event) {
        if (event == mProvider.orderPollFinanceId) {
          _showPaySuccessDialog(context);
        }
      });
    });
  }

  @override
  void dispose() {
    mProvider.orderPollFinanceId = '';
    mProvider.orderStatus.value = '';
    _orderMqttIdSubscription?.cancel();
    // 3. 释放焦点控制器资源
    _searchFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      // insetPadding: EdgeInsets.all(20),
      child: SizedBox(
        width: screenSize.width * 0.4,
        height: screenSize.height * 0.7,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Gaps.vGap15,
            _buildHeader(),
            Expanded(
              child: Container(
                width: double.infinity, // 宽度充满父容器
                alignment: Alignment.center, // 文本居中
                child: mProvider.isOnlyStore()
                    ? const Text('纯便利店商品暂不支持二维码', style: TextStyles.textBold24)
                    : Image.network(
                        widget.msg,
                        width: double.infinity, // 宽度充满父容器
                        height: double.infinity, // 高度充满父容器
                        fit: BoxFit.contain,
                      ),
              ),
            ),
            /*Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20), // 左右padding
              child: Container(
                width: double.infinity, // 宽度充满父容器
                alignment: Alignment.center, // 文本居中
                child: Text(mProvider.isOnlyStore() ? '' : '', style: TextStyles.textBold24),
              ),
            ),
            Gaps.vGap15,*/
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 80), // 左右padding
              child: Container(
                width: double.infinity, // 宽度充满父容器
                alignment: Alignment.center, // 文本居中
                child: SearchBox(
                  //key: _addKeyInput,
                  // 4. 将焦点控制器绑定到SearchBox
                  focusNode: _searchFocusNode,
                  hintText: '请用扫码枪扫描客户付款码...',
                  inputType: TextInputType.number,
                  // 点击事件
                  onSubmitted: (text) {
                    mProvider.orderPay(
                      qrCode: text,
                      onSuccess: (data, orderDes) {
                        mProvider.orderPollFinanceId = data?.payResult?.orderFinanceId ?? '';
                        // 判断支付结果 是否需要轮询
                        switch (data?.payResult?.payStatus) {
                          case OrderPayStatus.SUCCESS_PAY:
                            _showPaySuccessDialog(context, successInfo: orderDes);
                            break;
                          case OrderPayStatus.FAIL_PAY:
                          case OrderPayStatus.CANCEL_PAY:
                            showDialog<void>(context: context, builder: (context) => ErrorDialog(errorMessage: orderDes));
                            break;
                          case OrderPayStatus.UNPAID_PAY:
                          case OrderPayStatus.PAYING_PAY:
                            mProvider.pollOrderStatus(
                              onSuccess: () {
                                _showPaySuccessDialog(context, successInfo: orderDes);
                              },
                              onError: (msg) {
                                showDialog<void>(context: context, builder: (context) => ErrorDialog(errorMessage: msg));
                              },
                            );
                            break;
                          default:
                            showDialog<void>(context: context, builder: (context) => ErrorDialog(errorMessage: orderDes));
                        }
                      },
                      onError: (msg) {
                        showDialog<void>(context: context, builder: (context) => ErrorDialog(errorMessage: msg));
                      },
                    );
                  },
                ),
              ),
            ),
            Gaps.vGap15,
            Obx(() => Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20), // 左右padding
                  child: Container(
                    width: double.infinity, // 宽度充满父容器
                    alignment: Alignment.center, // 文本居中
                    child: Text(mProvider.orderStatus.value, style: TextStyles.textBold24.copyWith(color: Colours.redFF6634)),
                  ),
                )),
            Gaps.vGap15,
          ],
        ),
      ),
    );
  }

  void _showPaySuccessDialog(BuildContext context, {String successInfo = '支付成功'}) {
    mProvider.reset();
    showDialog<void>(
      context: context,
      builder: (context) {
        return PaySuccessDialog(
          successInfo: successInfo,
          onConfirm: () {
            Navigator.of(context).pop();
          },
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildHeader() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        const SizedBox(width: 20),
        Text('移动支付', style: TextStyles.textBold24.copyWith(color: Colours.dark_bg_color)),
        // Row(
        //     // 垂直方向基于基线对齐
        //     crossAxisAlignment: CrossAxisAlignment.baseline,
        //     // 指定使用字母基线
        //     textBaseline: TextBaseline.alphabetic,
        //     children: <Widget>[
        //       const SizedBox(width: 20),
        //       Text('合并油单', style: TextStyles.textBold24.copyWith(color: Colours.dark_bg_color)),
        //       /*RichText(
        //         text: TextSpan(
        //           children: [
        //             TextSpan(
        //               text: str,
        //               style: TextStyles.textSize16.copyWith(color: Colours.green),
        //             ),
        //             TextSpan(
        //               text: '的油单，请选择进行合并收款',
        //               style: TextStyles.textSize16.copyWith(color: Colours.orange),
        //             ),
        //           ],
        //         ),
        //       ),*/
        //     ]),
        IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            if (mProvider.orderPollFinanceId.isNotEmpty) {
              showElasticDialog<void>(
                context: context,
                barrierDismissible: false,
                builder: (BuildContext mContext) {
                  return BaseDialog(
                    title: '提示',
                    child: const Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.0),
                      child: Text('客户支付中..是否取消等待？\n支付结果请自行前往订单列表查询', textAlign: TextAlign.center),
                    ),
                    onPressed: () {
                      Navigator.of(mContext).pop();
                      Navigator.of(context).pop();
                    },
                  );
                },
              );
            } else {
              Navigator.of(context).pop();
            }
          },
        ),
      ],
    );
  }
}
